﻿using System;
using System.Collections.Generic;
using System.Configuration;
using WebSocket.App_Code.Model;
using System.Data.SQLite;

namespace WebSocket
{
    public class Global : System.Web.HttpApplication
    {
        /// <summary>
        /// 全局连接对象
        /// </summary>
        public static SQLiteConnection SQLiteConn { get; set; }

        protected void Application_Start(object sender, EventArgs e)
        {
            string ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            SQLiteConnection conn = new SQLiteConnection(ConnectionString);
            conn.Open();
            SQLiteConn = conn;

            List<string> ListTableSql = new List<string>();
            //打开外建约束
            ListTableSql.Add("pragma foreign_keys=on");
            //用户表
            ListTableSql.Add("create table Users(UserID integer primary key autoincrement,UserName text,LoginTime datatime default current_timestamp,LoginOutTime datatime,RecordStatus varchar(10) default 'Active')");
            //记录表
            ListTableSql.Add("create table SocketMsg(MsgID integer primary key autoincrement,CreateUserID integer,MsgDate datatime default current_timestamp,MsgIP text default '127.0.0.1',MsgVal text,RecordStatus varchar(10) default 'Active',foreign key(CreateUserID) references Users(UserID))");
            //记录接收人
            ListTableSql.Add("create table MsgToUsers(id integer primary key autoincrement,MsgID integer,UserID integer,RecordStatus varchar(10) default 'Active',foreign key(MsgID) references SocketMsg(MsgID),foreign key(UserID) references Users(UserID))");

            ListTableSql.Add("insert into Users (UserName) values('HuangNing')");
            ListTableSql.Add("insert into Users (UserName) values('LiuJu')");
            ListTableSql.Add("insert into Users (UserName) values('LiuJue')");

            ListTableSql.Add("insert into SocketMsg(CreateUserID,MsgIP,MsgVal) values(1,'10.122.10.79','Test Msg Val001')");
            ListTableSql.Add("insert into SocketMsg(CreateUserID,MsgIP,MsgVal) values(2,'10.122.10.79','Test Msg Val002')");
            ListTableSql.Add("insert into SocketMsg(CreateUserID,MsgIP,MsgVal) values(3,'10.122.10.79','Test Msg Val003')");

            ListTableSql.Add("insert into MsgToUsers(MsgID,UserID) values(1,2)");
            ListTableSql.Add("insert into MsgToUsers(MsgID,UserID) values(1,3)");
            ListTableSql.Add("insert into MsgToUsers(MsgID,UserID) values(2,1)");
            ListTableSql.Add("insert into MsgToUsers(MsgID,UserID) values(3,2)");

            
            using (SQLiteCommand comm = new SQLiteCommand(conn))
            {
                SQLiteTransaction Transaction = conn.BeginTransaction();
                comm.Transaction = Transaction;
                try
                {
                    foreach (string TableSql in ListTableSql)
                    {
                        comm.CommandText = TableSql;
                        comm.ExecuteNonQuery();
                    }
                    Transaction.Commit();
                }
                catch (Exception ex)
                {
                    Transaction.Rollback();
                    comm.Dispose();
                    throw new ApplicationException(ex.Message);
                }
                finally
                {
                    comm.Dispose();
                }
            }
        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {

        }

        protected void Session_End(object sender, EventArgs e)
        {
            Users user = Session["User"] as Users;
            Application.Lock();
            //通知所有用户,有新的用户登陆
            for (int i = 0; i < Application.AllKeys.Length; i++)
            {
                string KeyName = Application.AllKeys[i].ToString();
                if (KeyName.Length > 8 && KeyName.Substring(0, 8) == "UserOut_")
                {
                    Application[KeyName] = true;
                }
            }
            Application.Remove("UserLogin_" + user.UserID.ToString());
            Application.Remove("UserOut_" + user.UserID.ToString());
            Application.Remove("NewMsg_" + user.UserID.ToString());
            Application.UnLock();

            //删除发送给此用户,和此用户发送的所有信息
            MsgToUsers mtu = new MsgToUsers();
            mtu.UserID = user.UserID;
            mtu.Delete(MsgToUsersDeleteType.UserID);

            SocketMsg sm = new SocketMsg();
            sm.UserID=user.UserID;
            sm.Delete(SocketMsgDeleteType.UserID);

            //删除用户
            user.Delete();
        }

        protected void Application_End(object sender, EventArgs e)
        {

        }
    }
}